
module.exports = {
  cacl: cacl,
  max: max,
  min: min,
  sum: sum,
  avg: avg,
  use: use,
  first: first,
  last: last
}
function cacl (arr, callback) {
  var ret
  for (var i = 0; i < arr.length; i++) {
    ret = callback(arr[i], ret)
  }
  return ret
}

function max (arr) {
  return cacl(arr, (item, max) => {
    if (!(max > item)) {
      return item
    } else {
      return max
    }
  })
}

function min (arr) {
  return cacl(arr, (item, min) => {
    if (!(min < item)) {
      return item
    } else {
      return min
    }
  })
}

function sum (arr) {
  return cacl(arr, (item, sum) => {
    if (typeof (sum) === 'undefined') {
      return item
    } else {
      return toDecimal(sum += item)
    }
  })
}

function avg (arr) {
  if (arr.length === 0) {
    return 0
  }
  return toDecimal(sum(arr) / arr.length)
}

function use (arr) {
  let newArr = arr.filter((element, index, array) => {
    return (element > 0)
  })
  return toDecimal(max(newArr) - min(newArr))
}

function first (arr, callback) {
  let ret
  if (arr.length > 0) {
    ret = arr[0]
  } else {
    ret = 0
  }
  return ret
}

function last (arr, callback) {
  let ret
  if (arr.length > 0) {
    ret = arr[arr.length - 1]
  } else {
    ret = 0
  }
  return ret
}

function toDecimal (x) {
  var f = parseFloat(x)
  if (isNaN(f)) {
    return
  }
  f = Math.round(x * 100) / 100
  return f
}
